package ans.p145;

import ans.base.TreeNode;

import java.util.*;

/**
 * #      145
 * 名称   二叉树的后序遍历
 * 链接   https://leetcode-cn.com/problems/binary-tree-postorder-traversal
 * 题解   [1112](https://leetcode-cn.com/problems/binary-tree-postorder-traversal/solution)
 * 通过率 74.4%
 * 难道   中等
 */

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }

        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode prev = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == prev) {
                res.add(root.val);
                prev = root;
                root = null;
            } else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }

}